package test.gwtlearning.Step2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.GeneralSecurityException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringEscapeUtils;

import test.gwtlearning.storage.TokenStore;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gdata.client.Service;
import com.google.gdata.client.Service.GDataRequest;
import com.google.gdata.client.docs.DocsService;
import com.google.gdata.client.http.AuthSubUtil;
import com.google.gdata.util.AuthenticationException;

public class FetcherServlet extends HttpServlet {

	private UserService userService = UserServiceFactory.getUserService();
	private DocsService docsService = new DocsService("google-feedfetcher-v1");

	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws IOException {

		res.setContentType("text/html");
		String sessionToken = null;

		if (userService.isUserLoggedIn()) {
			User user = userService.getCurrentUser();
			sessionToken = TokenStore.getToken(user.getUserId());
		}

		if (sessionToken == null) {

			String authToken = null;
			try {
				authToken = AuthSubUtil.getTokenFromReply(req.getQueryString());
			} catch (Exception ex) {
			}

			if (authToken == null) {
				res.getWriter().print(
						"<a href=\""
								+ userService.createLoginURL(req
										.getRequestURL().toString())
								+ "\">Log in</a>");

				String nextUrl = req.getRequestURL().toString();
				String requestUrl = AuthSubUtil.getRequestUrl(nextUrl,
						"https://docs.google.com/feeds/", false, true);
				res.getWriter()
						.print("<a href=\""
								+ requestUrl
								+ "\">Request token for the Google Documents Scope</a>");
				return;
			} else {
				try {
					sessionToken = AuthSubUtil.exchangeForSessionToken(
							authToken, null);
					if (userService.isUserLoggedIn()) {
						User user = userService.getCurrentUser();
						TokenStore.addToken(user.getUserId(), sessionToken);
					}
				} catch (AuthenticationException e) {
					// Handle
				} catch (GeneralSecurityException e) {
					// Handle
				} catch (NullPointerException e) {
					// Ignore
				}
			}
		}

		if (sessionToken != null) {
			try {
				res.getWriter()
						.print("<h3>A Google Data session token was found for your account!</h3>");
				res.getWriter().print(
						"<p>Token: " + sessionToken + "</p><br />");

				docsService.setAuthSubToken(sessionToken);
				GDataRequest feedRequest = docsService
						.createFeedRequest(new URL(
								"https://docs.google.com/feeds/default/private/full"));
				feedRequest.execute();

				StringBuilder builder = new StringBuilder();
				String line;

				try {
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(
									feedRequest.getResponseStream(), "UTF-8"));

					while ((line = reader.readLine()) != null) {
						builder.append(line).append("\n");
					}
				} finally {
					feedRequest.getResponseStream().close();
				}

				String feed = builder.toString();
				res.getWriter().print(
						"<p style=\"font-family:Courier New; "
								+ "white-space:nowrap;\"><br />");
				res.getWriter().print(StringEscapeUtils.escapeXml(feed));
				res.getWriter().print("</p><br />");

			} catch (Exception ex) {
				res.getWriter().print("<h1>Failure</h1>");
				if (userService.isUserLoggedIn()) {
					User user = userService.getCurrentUser();
					TokenStore.deleteToken(user.getUserId());
				}
			}
		} else {

		}
	}
}
